package ink.xiaobaibai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ink.xiaobaibai.common.CouponStatus;
import ink.xiaobaibai.common.ServiceResult;
import ink.xiaobaibai.dao.CouponDao;
import ink.xiaobaibai.entity.ClientUser;
import ink.xiaobaibai.entity.Coupon;
import ink.xiaobaibai.entity.CouponUser;
import ink.xiaobaibai.service.IClientUserService;
import ink.xiaobaibai.service.ICouponService;
import ink.xiaobaibai.service.ICouponUserService;
import ink.xiaobaibai.serviceOxy.IRedisUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2021-06-05
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponDao, Coupon> implements ICouponService {

    @Autowired
    private ICouponUserService couponUserService;

    @Autowired
    private IClientUserService clientUserService;

    @Autowired
    private IRedisUtils redisUtils;

    @Override
    public List<Coupon> getCanReceiveCouponByUserId(Integer userId) {
        return this.baseMapper.getCanReceiveCouponByUserId(userId);
    }

    @Override
    public ServiceResult receiveThisCouponById(Integer couponId, Integer userId) {
        //数量 未停用 生效中
        QueryWrapper<Coupon> q1 = new QueryWrapper<>();
        q1.select("id", "deadline", "stop_use", "remaining_count", "useful_day", "phone_flag");
        q1.eq("id", couponId);
        Coupon coupon = this.getOne(q1);
        if (coupon == null || coupon.getStopUse() || coupon.getRemainingCount() <= 0 || coupon.getDeadline().getTime() < System.currentTimeMillis()) {
            return ServiceResult.fail("优惠券领取失败");
        }
        if (coupon.getPhoneFlag()) {
            // 为手机号标识
            QueryWrapper<ClientUser> q2 = new QueryWrapper<>();
            q2.select("id", "user_phone");
            q2.eq("id", userId);
            ClientUser clientUser = this.clientUserService.getOne(q2);
            if (clientUser.getUserPhone() == null) {
                return ServiceResult.fail("当前优惠券需要授权手机号后领取");
            }
        }
        //未领取过
        QueryWrapper<CouponUser> q3 = new QueryWrapper<>();
        q3.eq("coupon_id", couponId);
        q3.eq("user_id", userId);
        if (this.couponUserService.count(q3) == 1) {
            return ServiceResult.fail("不可重复领取");
        }
        //剩余数量-1
        coupon.setRemainingCount(coupon.getRemainingCount() - 1);
        this.updateById(coupon);
        //设置好过期时间放入
        CouponUser couponUser = new CouponUser(couponId, userId, DateUtils.addDays(new Date(), coupon.getUsefulDay()), CouponStatus.CAN_USE.getStatus());
        this.couponUserService.save(couponUser);
        return ServiceResult.ok();
    }

    @Override
    public void consumeCoupon(String orderId, Integer userId) {
        Integer couponId = this.redisUtils.getCoupon(orderId);
        if (couponId != null) {
            // 消耗这张
            UpdateWrapper<CouponUser> u1 = new UpdateWrapper<>();
            u1.eq("coupon_id", couponId);
            u1.eq("user_id", userId);
            u1.set("status", CouponStatus.USED.getStatus());
            this.couponUserService.update(u1);
            UpdateWrapper<Coupon> u2 = new UpdateWrapper<>();
            u2.eq("id", couponId);
            u2.setSql("use_count=use_count+1");
            this.update(u2);
        }
    }

}
